import axios, { AxiosError, AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from "@ohos/axios"

export class HttpUtils{

  static base_url:string = 'https://8aa772c1beb48faa6afc224809dec4b8.loophole.site'
  // static base_url:string = 'http://172.27.144.1:80'

  private static instance:HttpUtils
  // https://9ef58c1ac53bc5880911195bd1ddd0e4.loophole.site
  static axiosInstance:AxiosInstance

  static getInstance(headerType?:number){
    if(this.instance==null){
      this.instance = new HttpUtils()
      this.axiosInstance = axios.create({
        baseURL:this.base_url,
        timeout:5000,
        headers:headerType===0?{
          'Content-Type': 'application/json'
        }:{
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      })
      this.axiosInstance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
        config.headers['token']=AppStorage.get('token')
        console.log(`http config:${JSON.stringify(config)}`)
        return config;
      }, (err: AxiosError) => {
        return Promise.reject(err);
      })
      this.axiosInstance.interceptors.response.use((response: AxiosResponse) => {
        return response.data;
      }, (err: AxiosError) => {
        return Promise.reject(err);
      })
    }
    return this.instance
  }

  post(url:string,data:any){
    return HttpUtils.axiosInstance.post(
      url,
      data
    )
  }

  get(url:string,data?:any){
    return HttpUtils.axiosInstance.get(url,{
      data
    })
  }
}